import React, { useState, useEffect } from 'react';
import request from '../../../http';
import moment from 'moment';
import { DatePicker, Space, Modal } from 'antd';
import { Select, Image, Descriptions, Upload, Divider, Input } from 'antd';
import { Button, Menu, Dropdown, Form, Radio } from 'antd';
const { RangePicker } = DatePicker;
import { Table } from 'antd';
const { Option } = Select;
import { history } from 'umi';
import '../../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import draftToMarkdown from 'draftjs-to-markdown'; //获取编辑框得内容

import '../work/approval.css';
// 冯小建--作业批复页

// 表单布局
const formItemLayout = {
  labelCol: {
    // xs: { span: 24 },
    // sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

//顶部选择按钮初始状态
const btnStatus = [1, 0, 0];

const approval = () => {
  // 表单
  const [form] = Form.useForm();
  // 表单查询提交
  const [submitForm, setSubmitForm] = useState();
  // 作业答案
  const [answerInfo, setAnswerInfo] = useState({
    answerContent: '',
  });
  // 顶部选择按钮
  const [btnStyle, setBtnStyle] = useState(btnStatus);
  // 富文本内容
  const [editorState, setEditorState] = useState();
  const [editorContent, setEditorContent] = useState();

  //作业任务信息
  const [workInfo, setWorkInfo] = useState(btnStatus);
  // 传值作业id、类型
  const [workIdInfo, setWorkId] = useState(0);
  const [workType, setWorkType] = useState(0);

  // 作业信息任务接口
  const getWorkInfo = (workId) => {
    console.log('执行-作业信息任务接口workId:', workId);
    request
      .post('/homeworksec/t_s/showHomeworkInfo', {
        workId: workId,
      })
      .then((response) => {
        // 判断
        if (response.code === 20000) {
          // 成功
          console.log('作业', response.data);
          response.data && setWorkInfo(response.data); //设置
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 获取回答答案
  const getAnswerInfo = (workId) => {
    console.log('执行-答案接口');
    request
      .post('/homeworksec/teacher/showHomeworkAnswer', {
        sumbitId: workId,
      })
      .then((response) => {
        // 判断
        if (response.code === 20000) {
          // 成功
          console.log('答案', response.data);
          response.data && setAnswerInfo(response.data); //设置
        } else {
          // alert(response.message);
          console.log(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 上传附件
  const normFile = (e: any) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 富文本变化
  const onEditorStateChange = (editorState) => {
    // console.log(convertToRaw(editorState.getCurrentContent()))
    setEditorState(editorState);
  };
  //获取内容变化值
  const onEditorChange = (editorContent) => {
    // console.log(JSON.stringify(editorContent));
    setEditorContent(editorContent);
  };
  // 查询
  const onFinish = (fieldsValue: any) => {
    const editorContent = draftToMarkdown(
      convertToRaw(editorState.getCurrentContent()),
    );
    const approvalDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') || ''; //当前时间
    const values = {
      // ...fieldsValue,
      approvalDate: approvalDate,
      score: parseInt(fieldsValue['score']) || 0,
      // 'comment': fieldsValue['comment'] || "",
      comment: editorContent || '',
      submitId: workIdInfo,
    };
    setSubmitForm(values);
    values && showModal();
    console.log('Received values of form: ', fieldsValue, values);
  };

  // 重置
  const onReset = () => {
    setSubmitForm({
      annex_id: 0,
      completion_time: '',
      course_id: 0,
      p_g_id: '',
      release_time: '',
      s_id: '',
      submitTime: '',
      teacherId: '',
      type: 0,
      work_content: '',
      work_theme: '',
    });
    form.resetFields();
  };

  // 初加载
  useEffect(() => {
    const { query = {} } = history.location;
    console.log('获取的wokid', query.submitId);
    setWorkId(parseInt(query.submitId));
    setWorkType(parseInt(query.statuType));
    // 获取初始值
    getWorkInfo(parseInt(query.submitId));
    getAnswerInfo(parseInt(query.submitId));
  }, []);

  const [visible, setVisible] = React.useState(false);
  const [confirmLoading, setConfirmLoading] = React.useState(false);
  const [modalText, setModalText] = React.useState('确定要批复吗？');

  const showModal = () => {
    setVisible(true);
  };

  const handleOk = () => {
    setModalText('正在发布...');
    setConfirmLoading(true);
    setTimeout(() => {
      setVisible(false);
      setConfirmLoading(false);
      // 执行发布作业
      request
        .post('/homeworksec/teacher/addScore', submitForm)
        .then((response) => {
          console.log(response);
          // 判断
          if (response.code === 20000) {
            console.log('批复成功');
            Modal.success({
              content: '批复成功！',
            });
            history.push('/teacher/work/correct');
          } else {
            // alert(response.message);
            Modal.error({
              title: '失败',
              content: response.message,
            });
          }
        })
        .catch((error) => {
          console.log(error);
          Modal.error({
            title: '失败',
            content: '批复失败',
          });
        });
    }, 2000);
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setVisible(false);
  };

  return (
    <div>
      {/* 顶部选择按钮 */}
      <div className="btn-box">
        <Button
          className={btnStyle[0] === 1 ? 'isPointed' : 'noPointed'}
          onClick={() => {
            setBtnStyle([1, 0, 0]);
          }}
          size="large"
        >
          作业任务
        </Button>
        <Button
          className={btnStyle[1] === 1 ? 'isPointed' : 'noPointed'}
          onClick={() => {
            setBtnStyle([0, 1, 0]);
          }}
          size="large"
        >
          学生答辩
        </Button>
        <Button
          className={btnStyle[2] === 1 ? 'isPointed' : 'noPointed'}
          onClick={() => {
            setBtnStyle([0, 0, 1]);
          }}
          size="large"
        >
          老师批复
        </Button>
      </div>

      {/* 1 作业任务 */}
      {btnStyle[0] === 1 ? (
        <div className="part">
          <div className="workContent">
            <h1>{workInfo.workTheme}</h1>
            <p>{workInfo.workContent}</p>
            {/* <Image
            width={200}
            height={200}
            src="erro"
            fallback=""
          /> */}
            {/* 相关附件 */}
            {workInfo.annexId ? (
              <div>
                <Divider />
                <h3>附件:</h3>
              </div>
            ) : null}
          </div>

          <Descriptions title="" bordered>
            <Descriptions.Item label="发布人">
              {workInfo.userName}
            </Descriptions.Item>
            <Descriptions.Item label="发布时间">
              {workInfo.releaseDateTime}
            </Descriptions.Item>
            <Descriptions.Item label="计划时间">
              {workInfo.completionDateTime}
            </Descriptions.Item>
          </Descriptions>
        </div>
      ) : null}

      {/* 2 学生答辩 */}
      {btnStyle[1] === 1 ? (
        <div className="part">
          <h1>相关附件：</h1>
          <Divider />
          <div>
            答辩内容：
            <Input.TextArea
              style={{ height: '100px' }}
              value={answerInfo.answerContent}
              disabled
            />
          </div>
        </div>
      ) : null}

      {/* 3 老师批复 */}
      {btnStyle[2] === 1 ? (
        <div className="part">
          {/* 表单 */}
          <Form onFinish={onFinish} form={form}>
            <Form.Item
              style={{ width: '20%' }}
              className="form-item"
              name="score"
              label="得分"
              rules={[{ required: true }]}
            >
              <Input placeholder="请录入" />
            </Form.Item>

            {/* 上传附件 */}
            <Form.Item
              name="upload"
              label="相关附件"
              valuePropName="fileList"
              getValueFromEvent={normFile}
              extra=""
            >
              <Upload name="logo" action="/upload.do" listType="picture">
                <Button className="ant-btn ant-btn-primary addLeave">
                  上传附件
                </Button>
              </Upload>
            </Form.Item>

            {/* 富文本 */}
            <Form.Item name="comment">
              <div>
                <Editor
                  // editorState={editorState}
                  wrapperClassName="demo-wrapper"
                  editorClassName="demo-editor"
                  editorState={editorState}
                  onContentStateChange={onEditorChange} //获取内容变化值
                  onEditorStateChange={onEditorStateChange} //编辑器状态发生变化时
                />
                {/* <textarea
                    disabled
                  // value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
                  /> */}
              </div>
            </Form.Item>

            {/* 按钮 */}
            <Form.Item>
              <Button type="primary" htmlType="submit">
                确认提交
              </Button>
              <Modal
                title="批复作业"
                visible={visible}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
              >
                <p>{modalText}</p>
              </Modal>
              <Button htmlType="button" style={{ marginLeft: '10px' }}>
                保存草稿
              </Button>
            </Form.Item>
          </Form>
        </div>
      ) : null}
    </div>
  );
};
export default approval;
